/**
 * Copyright (C), 2015-2018, XXX有限公司
 * FileName: UserController
 * Author:   周宏硕
 * Date:     2018/10/30 9:29
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.htwx.controller;

import com.htwx.entity.FactoryLocation;
import com.htwx.entity.SubmissionReport;
import com.htwx.entity.Tool;
import com.htwx.entity.User;
import com.htwx.service.FactoryLocationService;
import com.htwx.service.SubmissionReportService;
import com.htwx.service.UserService;

import java.io.FileInputStream;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


/**
 * @author 周宏硕
 * @create 2018/10/30
 * @since 1.0.0
 */
@RestController
@RequestMapping("/UserController")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private SubmissionReportService submissionReportService;
    @Autowired
    private FactoryLocationService factoryLocationService;

    public String workPath = "F:\\develop\\apache-tomcat-8.5.35\\webapps\\ROOT\\images\\";

    //存放图片地址集合
    int i = 0;
    List<String> images = new ArrayList<String>();
    String address = null;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String downloadFile(@RequestParam("files") MultipartFile files, HttpServletRequest request) {
        if (!files.isEmpty()) {
            Tool tool = new Tool();
            if (files != null) {
                String dirPath = request.getServletContext().getRealPath("/images");
                System.out.println("dirPath:" + dirPath);
                File file = new File(dirPath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                String filename = files.getOriginalFilename();
                if (filename.endsWith("jpg") || filename.endsWith("png") || filename.endsWith("JPG") || filename.endsWith("PNG")) {
                    if (filename.endsWith("jpg")) {
                        filename = ".jpg";
                    } else if (filename.endsWith("png")) {
                        filename = ".png";
                    } else if (filename.endsWith("JPG")) {
                        filename = ".JPG";
                    } else if (filename.endsWith("PNG")) {
                        filename = ".PNG";
                    }
                    filename = UUID.randomUUID() + filename;
                    InputStream inStream;
                    FileOutputStream fs;
                    try {
                        files.transferTo(new File(dirPath + "/" + filename));
                        //System.out.println(workPath+"\\"+filename);
                        File filetwo = new File(dirPath + "/" + filename);
                        if (filetwo.exists()) {
                            inStream = new FileInputStream(dirPath + "/" + filename);
                            fs = new FileOutputStream(workPath + "/" + filename);
                            //加入图片集合
                            images.add(filename);
                            byte[] bt = new byte[1024];
                            int realbyte = 0;
                            while ((realbyte = inStream.read(bt)) > 0) {
                                fs.write(bt, 0, realbyte);
                            }
                            fs.close();
                            i += 1;
                            try {
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                try {
                                    if (inStream != null) {
                                        inStream.close();
                                    }
                                    if (fs != null) {
                                        fs.close();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } catch (IllegalStateException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    return "error";
                }
            } else {
                return "error";
            }
            address = tool.Splicing(images);
            System.out.println("处理好的图片集合：" + address);
            String a[] = address.split(",");
            for (int j = 0; j < a.length; j++) {
                System.out.println(j + ":" + a[j]);
            }
            return "welcome";
        } else {
            return "error";
        }
    }


    @RequestMapping("/insertReport")
    public String insertReport(String locationId, String details, String wxId, String whether_repair) {
        SubmissionReport submissionReport = new SubmissionReport();
        submissionReport.setLocationId(locationId);
        submissionReport.setDetails(details);
        submissionReport.setStatus(2);
        if (whether_repair.equals("yes")) {
            submissionReport.setWhether_repair(1);
        } else if (whether_repair.equals("no")) {
            submissionReport.setWhether_repair(2);
        }
        User user = new User();
        user.setWxId(wxId);
        submissionReport.setUser(user);
        System.out.println("address" + address);
        submissionReport.setPicture(address);
        String state = submissionReportService.insertSubmissionReport(submissionReport);
        if (state != "" && state != null) {
            address = null;
            images.clear();
        }

        return state;
    }

//    @RequestMapping(value = "/uploads",method = RequestMethod.POST)
//    public String downloadFile(@RequestParam("files") List<MultipartFile> files, HttpServletRequest request){
//        if(!files.isEmpty() && files.size() > 0){
//            System.out.println(files.size());
//            Tool tool = new Tool();
//            int i = 0;
//            List<String> images = new ArrayList<String>();
//            for (MultipartFile uploadfile : files) {
//                if(uploadfile != null && uploadfile.getSize() > 0){
//                    String dirPath = request.getServletContext().getRealPath("/images");
//                    System.out.println("dirPath:"+dirPath);
//
//                    File file = new File(dirPath);
//                    if(!file.exists()){
//                        file.mkdirs();
//                    }
//
//                    String filename = uploadfile.getOriginalFilename();
//                    if(filename.endsWith("jpg") || filename.endsWith("png") || filename.endsWith("JPG") || filename.endsWith("PNG")){
//                        filename = UUID.randomUUID()+"_"+filename;
//                        InputStream inStream ;
//                        FileOutputStream fs;
//                        try {
//                            uploadfile.transferTo(new File(dirPath+"/"+filename));
//                            //System.out.println(workPath+"\\"+filename);
//                            File filetwo = new File(dirPath+"/"+filename);
//                            if (filetwo.exists()) {
//                                inStream = new FileInputStream(dirPath+"/"+filename);
//                                fs = new FileOutputStream(workPath+"\\"+filename);
//                                //加入图片集合
//                                images.add(workPath+"\\"+filename);
//                                byte[] bt = new byte[1024];
//                                int realbyte = 0;
//                                while ((realbyte = inStream.read(bt)) > 0) {
//                                    fs.write(bt,0,realbyte);
//                                }
//                                fs.close();
//                                i += 1;
//
//                                try {
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                } finally {
//                                    try {
//                                        if (inStream != null) {
//                                            inStream.close();
//                                        }
//                                        if (fs != null) {
//                                            fs.close();
//                                        }
//                                    } catch (IOException e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            }
//                        } catch (IllegalStateException e) {
//                            // TODO Auto-generated catch block
//                            e.printStackTrace();
//                        } catch (IOException e) {
//                            // TODO Auto-generated catch block
//                            e.printStackTrace();
//                        } catch(Exception e){
//                            e.printStackTrace();
//                        }
//                        continue;
//                    }else {
//                        return "error";
//                    }
//                }else {
//                    return "error";
//                }
//            }
//
//            String address = tool.Splicing(images);
//            System.out.println("处理好的图片集合："+address);
//            String a[] = address.split(",");
//            for(int j = 0;j < a.length;j++){
//                System.out.println(j+":"+a[j]);
//            }
//            return "welcome";
//        }else {
//            return "error";
//        }
//
//
//    }


    @RequestMapping(value = "logincheck", method = RequestMethod.GET)
    public String tologin(String appid, String secretid, String jscode) {
//         appid = "wx431a80e5cb7ad48f";
//         secretid = "f9d6ccc8dcd5f30452a316452ba35c33";
//         jscode = "";
        String res = "";
        String line = null;
        try {
            URL url = new URL("https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secretid + "&js_code=" + jscode + "&grant_type=authorization_code");
            //URL url=new URL("https://www.baidu.com/");
            //通过url的openStream获取url对象所表示资源的字节输入流
            InputStream is = url.openStream();
            //将字节输入流转换为字符输入流
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            //为字符输入流添加缓冲
            BufferedReader br = new BufferedReader(isr);

            //读取数据
            while ((line = br.readLine()) != null) {
                //System.out.println(line);
                res += line;
            }
            br.close();
            isr.close();
            is.close();
            System.out.println(res);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }


    @RequestMapping(value = "/insertUser", method = RequestMethod.GET)
    public String insertUser(User user) {

        Integer insertUser = userService.insertUser(user);
        if (insertUser > 0) {
            return "ok";
        } else {
            return "error";
        }


    }

    //根据用户微信id查询用户信息
    @RequestMapping("getUserById")
    public List<User> getUserAll(String wxId) {
        return userService.findUserBywxId(wxId);
    }

    //根据用户id更新用户信息
    @RequestMapping("updateUserById")
    public String updateUserInfo(String userContacts, Integer userId, String userPhone) {
        User user = new User();
        user.setUserContacts(userContacts);
        user.setUserId(userId);
        user.setUserPhone(userPhone);
        return userService.updateUser(user);
    }


    //查询已完成没有评论的
    @RequestMapping(value = "findNotEvaluateById")
    public List<SubmissionReport> findNotEvaluateById(String wxId) {
        System.out.println(wxId);
        List<SubmissionReport> notEvaluateById = new ArrayList<SubmissionReport>();
        try {
            notEvaluateById = submissionReportService.findNotEvaluateById(wxId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return notEvaluateById;
    }

    //根据用户wx_id查询所提交的报表信息
    @RequestMapping(value = "findSubmissionReportById", method = RequestMethod.POST)
    public List<SubmissionReport> findUser(@RequestBody String wxId) {


        List<SubmissionReport> list = new ArrayList<SubmissionReport>();
        if (wxId != null) {
            list = submissionReportService.findSubmissionReportByWxId(wxId);
            return list;
        }
        return list;
    }

    @RequestMapping(value = "findSubmissionReportAll")
    public List<SubmissionReport> findSubmissionReportAll(Integer status) {
        List<SubmissionReport> list = new ArrayList<SubmissionReport>();

        list = submissionReportService.findSubmissionReportAll(status);
        System.out.println(list);
        return list;


    }

    //查询记录总数
    @RequestMapping(value = "findEvaluateCountById")
    public Integer findEvaluateCountById(String wxId) {
        return submissionReportService.findEvaluateCountById(wxId);
    }

    //修改
    @RequestMapping(value = "updateSubmissionReportByReportId")
    public String updateSubmissionReportByReportId(SubmissionReport submissionReport) {

        return submissionReportService.updateSubmissionReport(submissionReport);
    }


    //通过id删除报表信息
    @RequestMapping(value = "deleteSubmissionReport")
    public String deleteSubmissionReport(Integer reportId) {
        Integer result = submissionReportService.deleteSubmissionReport(reportId);
        if (result > 0) {
            return "ok";
        } else {
            return "no";
        }


    }


    //传单个或者数组进来

    @RequestMapping("findFactoryLocationById")
    public List<FactoryLocation> findTest(String factorylocationId) {

        List<FactoryLocation> list = new ArrayList<FactoryLocation>();
        try {
            list = factoryLocationService.findFactoryLocationBylocaitonId(factorylocationId);
            return list;
        } catch (Exception e) {

            return list;
        }

    }


    //查询所有位置信息，无参数
    @RequestMapping("getFactorylocationAll")
    public List<FactoryLocation> getFactorylocationAll() {

        List<FactoryLocation> list = new ArrayList<FactoryLocation>();

        try {
            list = factoryLocationService.getFactorylocationAll();
            return list;
        } catch (Exception e) {

            return list;
        }
    }


    //插入评论
    @RequestMapping(value = "updateEvaluate")
    public String updateEvaluate(SubmissionReport submissionReport) {

        Integer result = submissionReportService.updateEvaluate(submissionReport);
        if (result > 0) {
            return "ok";
        } else {
            return "null";
        }

    }


}
